package com.zhu.tool_test.util;

import com.alibaba.fastjson.JSONArray;
import core.MultipartData;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @program: tool_test
 * @description: 对json处理
 * @author: ggBall
 * @create: 2020-12-16 11:35
 **/
public class JsonUtils {

    public static Object dealData(Object o,String specificStr){

//        if (rootList.size() == 0) {
//            return rootList;
//        }

            Object obj = o;
            // 判断 data 是否是list
            if (obj instanceof List) {
                List<MultipartData> list = MultipartData.trans2MultipartData((List)obj);
                for (MultipartData data : list) {
                    dealData(data,specificStr);
                }

            } else if (obj instanceof Map) {
                // 将map 逐一遍历 判断是否有 specificStr 键名
                Map map = (Map) obj;
                Set<String> keys = map.keySet();
                for (String key : keys) {
                    if (key.contains(specificStr)) {
                        System.out.println("找到了 key = " + key);
                        System.out.println("找到了 value = " + map.get(key));
                    }
                    Object o1 = map.get(key);
                    dealData(o1,specificStr);

                }


            }

            return obj;
    }


    //读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Object readJsonFileToObj(String fileName) {
        String jsonFile = readJsonFile(fileName);
        return JSONArray.parse(jsonFile);
    }
}
